package joodin.impl.util;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import joodin.impl.application.util.ApplicationWrapper;
import my.stuff.vaadin.miglayout.util.ImageWrapper;

import com.vaadin.terminal.FileResource;

public class IconUtil {

	public static FileResource getIcon(final ImageWrapper image){
		File file = null;
		try {
			BufferedImage bimg = ImageIO.read(new File(image.getResource().getSourceFile().getAbsolutePath()));
			BufferedImage after = new BufferedImage(image.getWidth(), image.getHeight(), bimg.getType());
			AffineTransform at = new AffineTransform();
			at.scale((double)image.getWidth() / (double)image.getOriginalWidth(), (double)image.getHeight() / (double)image.getOriginalHeight());
			AffineTransformOp scaleOp = 
			   new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
			after = scaleOp.filter(bimg, after);
			file = new File("/tmp/image-" + image.hashCode() + ".png");
			file.deleteOnExit();
			ImageIO.write(after, "png", file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new FileResource(file, ApplicationWrapper.getInstance());
		
	}
		
}
